/**
 * 
 */
package com.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cyfex
 *
 */
public class StoreService {

	public static boolean storeAdd(String name, String room){
		
		Connection con = null;
		
		try {			
			con = DataBase.getConnection();
			PreparedStatement ps=con.prepareStatement("SELECT * FROM store_room WHERE name=?");
			ps.setString(1, name);
			if( !ps.executeQuery().next() ) {
				PreparedStatement psI=con.prepareStatement("INSERT INTO store_room(name,room) VALUES(?,?)");
				psI.setString(1, name);
				psI.setString(2, room);
				psI.execute();
			}else{
				con.close();
				return false;
			}
			
			con.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			if(con!=null)
				try {
					con.close();
				} catch (SQLException e1) {
					return false;
				}
			return false;
		}		
	}
	
	public static boolean storeEdit(String name, String room){
		
		Connection con = null;
		
		try {			
			con = DataBase.getConnection();
			PreparedStatement ps=con.prepareStatement("SELECT * FROM store_room WHERE name=?");
			ps.setString(1, name);
			if( ps.executeQuery().next() ) {
				PreparedStatement psU=con.prepareStatement("UPDATE store_room SET room=? WHERE name=?");
				psU.setString(1, room);
				psU.setString(2, name);
				psU.execute();
			}else{
				con.close();
				return false;
			}
			
			con.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			if(con!=null)
				try {
					con.close();
				} catch (SQLException e1) {
					return false;
				}
			return false;
		}
	}
	
	public static boolean storeDelete(HttpServletRequest request){

		Connection con = null;
		
		try {
			request.setCharacterEncoding("UTF-8");
			con = DataBase.getConnection();
			PreparedStatement psD=con.prepareStatement("DELETE FROM store_room WHERE name=?");
			String[] delSA = request.getParameterValues("delid");
			if( delSA!=null ){
				for( String delS:delSA ) {
					psD.setString(1, delS);
					psD.execute();
				}
			}
			else {
				return false;
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			if(con!=null)
				try {
					con.close();
				} catch (SQLException e1) {
					return false;
				}
			return false;
		}
	}
	
}
